<template>
    <div class="documentPage">
        <!-- 搜索添加 -->
        <el-form :model="form" :inline="true" class="myform">

            <div class="left">
                <el-form-item>
                    <el-input v-model="docVal" placeholder="文档名称或类型" />
                </el-form-item>
                <div class="demo-date-picker">
                    <div class="block">
                        <el-date-picker @change="fn1" v-model="value1" type="daterange" start-placeholder="开始时间"
                            end-placeholder="结束时间" value-format="x" range-separator="--" />
                    </div>
                </div>
                <el-form-item>
                    <el-button type="primary" :icon="Search" style="margin-left: 30px;" @click="toSerch">搜索</el-button>
                </el-form-item>
            </div>

            <div class="right">
                <el-form-item>
                    <el-button type="primary" @click="dialogFormVisible = true">
                        <el-icon style="font-size: 18px;">
                            <Plus />
                        </el-icon>
                        添加
                    </el-button>
                </el-form-item>
            </div>
        </el-form>

        <!-- 点击添加按钮 -->
        <el-dialog v-model="dialogFormVisible" title="课程文档">
            <el-form :model="form">
                <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
                    :size="formSize" status-icon>
                    <!-- 上传头像 -->
                    <el-form-item label="头像" prop="name">
                        <el-upload v-model:file-list="fileList" class="upload-demo" :auto-upload="false" multiple action=""
                            :http-request="httpRequest" :before-upload="beforeAvatarUpload" :show-file-list="true"
                            ref="uploadRef">
                            <template #trigger>
                                <el-button type="primary">选择文件</el-button>
                            </template>
                            <template #tip>
                                <div class="el-upload__tip">
                                    支持扩展名：.text .pdf .doc
                                </div>
                            </template>
                        </el-upload>
                    </el-form-item>
                </el-form>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">返回</el-button>
                    <!-- <el-button type="primary" @click="dialogFormVisible = false">
                        确认
                    </el-button> -->

                    <el-button type="primary" @click="submitUpload">
                        确认
                    </el-button>

                </span>
            </template>
        </el-dialog>

        <!-- 表格 -->

        <el-table :data="tableDataFittler?.slice((currentPage - 1) * pageSize, currentPage * pageSize)" :border="true"
            style="width: 100%">
            <el-table-column prop="id" label="序号" width="160" />
            <el-table-column prop="name" label="文档名称" width="300" />
            <el-table-column prop="type" label="文件格式" width="220" />
            <el-table-column prop="size" label="文件大小" width="220" />

            <el-table-column prop="time" label="上传时间" width="200">
                <template #default="{ row }">
                    <span>{{ dayjs.unix(row.time).format('YYYY-MM-DD') }}</span>
                </template>
            </el-table-column>
            <!-- 自定义删除按钮 -->
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" type="primary" :icon="Delete" circle
                        @click="handleDelete(scope.row.id)"></el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <el-pagination layout="prev, pager, next" :total="totalSize" v-model:page-size="pageSize"
            v-model:current-page="currentPage" class="pagination" />
    </div>
</template>

<script setup>
import { onMounted, reactive, ref, computed } from 'vue'
import { Search, Plus, Delete } from '@element-plus/icons-vue'
import { getDocument } from '../../api/user';
import { deleteItems } from '../../api/deleteData'
import { documentAdd } from "../../api/adds"
import dayjs from 'dayjs';

const currentPage = ref(1)
const pageSize = ref(10)
const maxTime = ref(null)
const minTime = ref(null)
const formSize = ref('default')
const ruleFormRef = ref()
const dialogFormVisible = ref(false)
const value1 = ref('')
const tableData = ref([])
const docVal = ref(null)
const tableDataFittler = ref([])
const uploadRef = ref("")
const fileList = ref([])

const form = reactive({
    name: '',
    region: '',
    date1: '',
    date2: '',
    delivery: false,
    type: [],
    resource: '',
    desc: '',
})

const rules = reactive({
    name: [
        { required: true, message: 'Please input Activity name', trigger: 'blur' },
        { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
})

const ruleForm = reactive({
    name: 'Hello',
})

const totalSize = computed(() => {
    return tableDataFittler.value?.length
})

const handleSizeChange = (val) => {
    pageSize.value = val
}

const handleCurrentChange = (val) => {
    currentPage.value = val
}

const fetchData = async () => {
    tableData.value = await getDocument()
    tableDataFittler.value = tableData.value
}

// 获取时间选择器选择的值
const fn1 = (timer) => {
    minTime.value = timer[0] / 1000
    maxTime.value = timer[1] / 1000
}

// 删除单条数据
const handleDelete = async (index) => {
    // 远程删除
    await deleteItems("document", `${index}`)
    // 本地删除
    tableDataFittler.value = tableDataFittler.value.filter((item) => item.id != index)
    tableData.value = tableData.value.filter((item) => item.id != index)
}

// 搜索
const toSerch = () => {
    // 筛选为空，直接赋值
    if (!docVal.value && !minTime.value) {
        tableDataFittler.value = tableData.value
        return
    }

    // 存在就过滤
    tableDataFittler.value = tableData.value.filter((item) => {
        return (docVal.value ? (item.name.includes(docVal.value) || item.type.includes(docVal.value)) : "false") && (minTime.value ? (minTime.value <= item.time && item.time <= maxTime.value) : "false")
    })
}

// 自定义post上传拦截
const httpRequest = () => { }

// 确认按钮被点击
const submitUpload = () => {
    uploadRef.value.submit()
    fileList.value?.forEach(async (item) => {
        const fileName = item.raw.name.split(".")[0]
        const fileType = item.raw.name.split(".")[1]
        const fileTime = dayjs().unix()
        const fileSize = `${parseInt(item.size / 1000)}kb`
        // console.log(fileName, fileSize, fileType, fileTime);
        console.log(tableData.value.length);

        const data = {
            name: fileName,
            type: fileType,
            size: fileSize,
            time: fileTime,
            operation: "删除"
        }

        // 云端添加
        await documentAdd(data)

        // 本地刷新
        location.reload()
    })

    // 令弹出框消失
    dialogFormVisible.value = false
}

const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type != 'application/pdf' && rawFile.type != 'text/plain' && rawFile.type != 'application/msword') {
        ElMessage.error('仅支持 text/pdf/doc 格式')
        return false
    }
    
    return true
}

onMounted(() => {
    fetchData()
})

</script>

<style scoped>
.documentPage {
    /* padding: 30px; */
    height: 100%;
    min-height: 600px;
    padding: 15px 20px;
}

.myform {
    display: flex;
    justify-content: space-between;
}

.left {
    display: flex;
}

.demo-date-picker .block:last-child {
    border-right: none;
}

.demo-date-picker .demonstration {
    display: block;
    color: var(--el-text-color-secondary);
    font-size: 14px;
    margin-bottom: 20px;
}

:deep(.cell) {
    text-align: center;
}

:deep(.el-input) {
    width: 150px;
}

.pagination {
    display: flex;
    justify-content: center;
    margin-top: 30px;
}

:deep(.el-table th) {
    background: rgb(236, 247, 255);
    color: rgb(102, 102, 102)
}
</style>
